package com.example.aliyuntest;

import android.os.Bundle;
import android.widget.EditText;

import androidx.activity.ComponentActivity;
import androidx.appcompat.app.AlertDialog;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.example.aliyuntest.databinding.ActivityMainBinding;
import com.example.aliyuntest.ui.TaskAdapter;
import com.example.aliyuntest.ui.TaskViewModel;

import java.util.ArrayList;

public class MainActivity extends ComponentActivity {

    private ActivityMainBinding binding;
    private TaskViewModel viewModel;
    private TaskAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        viewModel = new ViewModelProvider(this).get(TaskViewModel.class);

        adapter = new TaskAdapter(new ArrayList<>(), task -> viewModel.toggleTask(task.getId()));
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        binding.recyclerView.setAdapter(adapter);

        // 观察 LiveData，自动刷新 UI
        viewModel.getTasks().observe(this, tasks -> adapter.submitList(tasks));

        // 添加任务按钮
        binding.add.setOnClickListener(v -> {
            EditText input = new EditText(this);
            new AlertDialog.Builder(this)
                    .setTitle("新任务")
                    .setView(input)
                    .setPositiveButton("添加", (dialog, which) -> {
                        String title = input.getText().toString();
                        if (!title.isEmpty()) {
                            viewModel.addTask(title);
                        }
                    })
                    .setNegativeButton("取消", null)
                    .show();
        });

        adapter.setOnTaskLongClickListener(task -> {
            new AlertDialog.Builder(this)
                    .setTitle("删除任务")
                    .setMessage("确定要删除 \"" + task.getName() + "\" 吗？")
                    .setPositiveButton("删除", (dialog, which) -> {
                        viewModel.removeTask(task.getId());
                    })
                    .setNegativeButton("取消", null)
                    .show();
        });
    }
}
